<?php

namespace Biz\service\NewProduct;


use Biz\model\brandActivity\UserAddressModel;
use Biz\model\NewProduct\NewProductJdCardModel;
use Biz\model\NewProduct\NewProductWinnerListModel;
use Biz\model\trade\ShopCourier as mShopCourier;
use Biz\service\trade\ShopCourier as sShopCourier;
use Doraemon\cache\UserCounter;
use Doraemon\model\Member;
use Doraemon\service\Push\PushService;
use Doraemon\service\User;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\LinkFormat;
use Hhz\AdministrativeRegion\Region;
use Hhz\Medoo\Medoo;

class NewProductWinnerListService
{

    /**
     * @param array $ids
     * @return array
     */
    public static function getCountByNid(array $ids): array
    {
        if ($ids) {
            $where = [
                'nid' => $ids,
                'winner_status' => NewProductWinnerListModel::NOT_SEND_PRIZE,
                "GROUP" => "nid",
            ];

            return self::handleCount(NewProductWinnerListModel::getCountMaps($where), 'nid');
        } else {
            return [];
        }

    }

    /**
     * @param array $data
     * @param string $field
     * @return array
     */
    public static function handleCount(array $data, string $field): array
    {
        $res = [];
        foreach ($data as $item) {
            $res[$item[$field]] = $item['cnt'];
        }

        return $res;
    }

    /**
     * 获取活动中奖名单
     * @param array $field
     * @param array $where
     * @param $uid
     * @param $pageSize
     * @return array
     */
    public static function getWinnerList(array $field, array $where, $uid, $pageSize): array
    {
        $list = NewProductWinnerListModel::select($field, $where) ?? [];
        $res = [];
        if ($list) {
            unset($where['LIMIT']);
            $count = count(NewProductWinnerListModel::select($field, $where));
            $res ['total'] = $count;
            $res ['is_over'] = $pageSize < $count ? 0 : 1;
            $user_infos = User::getBrandCards(array_column($list, 'uid'), $uid);
            if (in_array('address_id', $field)) {
                $addressMap = self::handleData(UserAddressModel::getByIds(array_column($list, 'address_id')), 'id');
            }
            if (in_array('courier_id', $field)) {
                $couriersMap = self::handleData(mShopCourier::getByCourierIds(array_unique(array_column($list,
                    'courier_id'))), 'courier_id');
            }
            foreach ($list as $value) {
                $value['winner_status_name'] = NewProductWinnerListModel::WINNER_STATUS[$value['winner_status']] ?? '';
                $value['address_info'] = $addressMap[$value['address_id']] ?? [];
                $value['couriers_info'] = $couriersMap[$value['courier_id']] ?? [];
                $value['user_info'] = $user_infos[$value['uid']] ?? [];
                $value['counter'] = UserCounter::getOne($value['uid']) ?? [];
                if ($value['user_info']) {
                    $value['nickName'] = $value['user_info']['nick'] ?? '';
                }
                if ($value['address_info']) {
                    $infoAddress = '';
                    if ($value['address_info']['address']) {
                        $area = Region::getAreaDetailByCode($value['address_info']['area_code']);
                        $infoAddress = $value['address_info']['area_code'] ? $area . $value['address_info']['address'] : "";
                    }
                    $value['address_info_name'] = $value['address_info']['name'] ?? '';
                    $address_info_tel = '';
                    if (!empty($value['address_info']['tel'] )) {
                        $address_info_tel = \Biz\model\brandActivity\UserAddressModel::decryptPhone($value['address_info']['tel']);
                    }
                    $value['address_info_tel'] = $address_info_tel;
                    $value['address_info_address'] = $infoAddress;
                }
                if ($value['couriers_info']) {
                    $value['couriers_info_courier_name'] = $value['couriers_info']['courier_name'] ?? '';
                }
                $res['list'] [] = $value;
            }
        }

        return $res;
    }

    /**
     * @param array $data
     * @param string $field
     * @param string $key
     * @return array
     */
    public static function handleData(array $data, string $field, string $key = ''): array
    {
        $res = [];
        foreach ($data as $item) {
            if ($key) {
                $res[$item[$field]] = $item[$key];
            } else {
                $res[$item[$field]] = $item;
            }
        }

        return $res;
    }

    /**
     * @param $field
     * @param $where
     * @return array|mixed
     */
    public static function getWinnerInfo($field, $where)
    {
        $info = NewProductWinnerListModel::get($field, $where) ?? [];

        if ($info) {
            $info['user_info'] = User::getUser($info['uid']);
            $info['nickName'] = $info['user_info']['nick'] ?? '';
            if ($info['address_id'] > 0) {
                $info['address'] = UserAddressModel::first(['id' => $info['address_id']]) ?? [];
                $area = Region::getAreaDetailByCode($info['address']['area_code']);
                $info['address_info_name'] = $info['address']['name'] ?? '';
                $address_info_tel = '';
                if (!empty($info['address']['tel'] )) {
                    $address_info_tel = \Biz\model\brandActivity\UserAddressModel::decryptPhone($info['address']['tel']);
                    $info['address']['tel'] = $address_info_tel;
                }
                $info['address_info_tel'] = $address_info_tel;
                $info['address_info_address'] = $area . $info['address']['address'] ?? '';

                //修复接口数据使用
                $info['address']['address'] = $info['address_info_address'];
            } else {
                $info['address'] = [];
            }

            if ($info['courier_id'] > 0) {
                $info['couriers_info'] = mShopCourier::get('*', ['courier_id' => $info['courier_id']]);
                $info['couriers_info_courier_name'] = $info['couriers_info']['courier_name'] ?? '';
            }
            $info['couriers'] = static::getCourierList();

        }

        return $info;
    }

    /**
     * 获取物流列表
     */
    public static function getCourierList(): array
    {
        $courierList = sShopCourier::getCourierFileList();
        $showCourseIds = [1, 2, 3, 4, 5, 12, 13, 14, 20, 17, 38];

        return array_values(array_filter($courierList, function ($value) use ($showCourseIds) {
            return ($value['courier_id'] != mShopCourier::SELF_LIFTING_ID && in_array($value['courier_id'],
                    $showCourseIds));
        }));
    }

    /**
     * 根据物流单号推送push 系统消息
     * @param $tracking_num
     * @return bool
     * @throws \Exception
     */
    public static function pushSignMsg($tracking_num): bool
    {
        $uid = NewProductWinnerListModel::first(['tracking_number' => $tracking_num], 'uid');
        if (!$uid) {
            return false;
        }
        $nick = Member::getNickByUid($uid);
        $title = 'Hi' . $nick . '，恭喜你中奖啦！';
        $alert = '你参与「新品速递」活动的奖品显示已签收，快来晒图和住友一起分享吧！';
        $link = Hhzurl::getDomain() . '/brand/new-product-express';
        $link = LinkFormat::encryptionLink($link);
        $pushId = 'brand_awe_' . date('Y-m-d');
        $params = [
            'uid' => $uid,
            'title' => $title,
            'alert' => $alert,
            'param' => [
                'link' => $link,
                'push_id' => $pushId,
                'image' => '',
            ],
        ];

        PushService::send($params);
        $data = [
            'msgCode' => 0,
            'to_uid' => $uid,
            'msgParams' => [
                'title' => $title,
                'detail' => $alert,
                'img' => '',
                'link' => $link,
                'type' => 2,
            ],
        ];

        \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send', $data, \Doraemon\cache\Queue::QUEUE_DORAEMON);

        return true;
    }

    /**
     * @param array $ids
     * @return array
     */
    public static function getHasAddressCountByIds(array $ids): array
    {
        $where['nid'] = $ids;
        $where['winner_status'] = NewProductWinnerListModel::NOT_SEND_PRIZE;
        $where['GROUP'] = 'nid';

        return self::handleCount(NewProductWinnerListModel::select(['cnt' => Medoo::raw('count(nid)'), 'nid'], $where),
            'nid');
    }

    /**
     * @param array $ids
     * @return array
     */
    public static function getCountJdCardByNid(array $ids): array
    {
        if ($ids) {
            $where = [
                'nid' => $ids,
                "GROUP" => "nid",
            ];

            return self::handleCount(NewProductJdCardModel::getCountMaps($where), 'nid');
        } else {
            return [];
        }

    }

}